package com.h3c.ptability.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.h3c.ptability.entity.PtEsignScene;
import com.h3c.ptability.mapper.PtEsignSceneAttrMapper;
import com.h3c.ptability.entity.PtEsignSceneAttr;
import com.h3c.ptability.service.IPtEsignSceneAttrService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * 电子签场景属性定义（定义了根据用户的哪些属性找到对应的优先级最高的适用场景）实现类
 *
 * @author chenyifan
 * @since 2022-05-19 11:00:37
 */
@Service
public class PtEsignSceneAttrServiceImpl extends ServiceImpl<PtEsignSceneAttrMapper, PtEsignSceneAttr> implements IPtEsignSceneAttrService {

    @Override
    public Boolean judgeSuitScene(JSONObject userInfo, PtEsignScene esignScene) {
        boolean flag = true;
        List<PtEsignSceneAttr> sceneAttrs = list(new QueryWrapper<PtEsignSceneAttr>().lambda()
                .eq(PtEsignSceneAttr::getSceneId, esignScene.getSceneId())
        );
        if (sceneAttrs.size() > 0) {
            for (PtEsignSceneAttr sceneAttr : sceneAttrs) {
                List<String> split = StrUtil.split(sceneAttr.getAttrFieldValue(), ",");
                Object fieldValue = userInfo.get(sceneAttr.getAttrFieldName());
                if(Objects.isNull(fieldValue)){
                    flag = false;
                }else if (fieldValue instanceof String) {
                    flag = split.contains(String.valueOf(fieldValue));
                } else if (fieldValue instanceof Long || fieldValue instanceof Integer) {
                    flag = split.contains(String.valueOf(fieldValue));
                } else if (fieldValue instanceof BigDecimal) {
                    flag = split.contains(fieldValue.toString());
                }
                if (!flag) {
                    break;
                }
            }
        }
        return flag;
    }

    @Override
    public List<PtEsignSceneAttr> getAttrBySceneId(String sceneId) {
        QueryWrapper<PtEsignSceneAttr> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PtEsignSceneAttr::getSceneId, sceneId);
        return list(queryWrapper);
    }

    @Override
    public void deleteSceneAttrBySceneId(String sceneId) {
        QueryWrapper<PtEsignSceneAttr> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PtEsignSceneAttr::getSceneId, sceneId);
        remove(queryWrapper);
    }
}

